﻿namespace SharePointCSVImporter
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Windows;
    using System.Windows.Controls;

    using CSVParser;

    public partial class MainPage : UserControl
    {
        #region Fields

        public FieldConfigurationPopup config;

        Configuration currentConfig;
        FileInfo dataFile;
        private string errorLogText;
        private bool isConfigured;
        private ListItemUpdater updater;

        #endregion Fields

        #region Constructors

        public MainPage()
        {
            InitializeComponent();
        }

        #endregion Constructors

        #region Properties

        public bool IsConfigured
        {
            get { return isConfigured; }
            set { isConfigured = value; OnConfigured(value); }
        }

        #endregion Properties

        #region Methods

        internal void FinishedUpdating(bool success, string message)
        {
            Dispatcher.BeginInvoke(delegate()
            {
                UpdateProgress(message, 100);
                System.Threading.Thread.Sleep(2000);
                this.ProgressPanel.Visibility = System.Windows.Visibility.Collapsed;
            });
        }

        internal void ProcessFinished(Logger.Logger logger)
        {
            Dispatcher.BeginInvoke(delegate()
               {
               if (logger != null)
               {
                   string resultMessage;
                   string deleteMessage = "";
                   if (logger.ItemsDeleted > 0)
                   {
                       deleteMessage = logger.ItemsDeleted + " duplicate items were deleted.";
                   }
                   if (logger.ContainsErrors)
                   {
                       resultMessage = "Process Completed, but errors occurred.\r\nThere were "
                           + logger.LogCount + "CSV line items and " + logger.SuccessCount + " were successful." + deleteMessage
                           + "\r\n" + logger.ErrorCount + " updates were NOT successful.";

                       errorLogText = Logger.Logger.GetErrorLogText(logger);
                       if (!string.IsNullOrEmpty(errorLogText))
                       {
                           DownloadErrorReportButton.Visibility = System.Windows.Visibility.Visible;
                       }
                   }
                   else
                   {
                       resultMessage = "Process Completed, " + logger.SuccessCount + " items successfully imported from " + logger.LogCount + " CSV line items.\r\n" + deleteMessage;
                   }
                   ResultStackPanel.Visibility = System.Windows.Visibility.Visible;
                   ProcessCompleteResultTextBlock.Text = resultMessage;
               }

               });
        }

        private void ConfigureButton_Click(object sender, RoutedEventArgs e)
        {
            if (dataFile != null)
            {
                if (config == null)
                {
                    List<string> csvFields = CSVParser.CSVParseFirstLine(dataFile.OpenRead());
                    config = new FieldConfigurationPopup(csvFields);

                    config.Closed += config_Closed;
                }
                config.Show();
            }
        }

        void config_Closed(object sender, EventArgs e)
        {
            if (config != null && config.DialogResult != null && config.DialogResult == true)
            {
                this.IsConfigured = true;
                this.currentConfig = config.StoredConfig;
            }
        }

        private void DownloadErrorReport_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(errorLogText))
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "(*.txt)|*.txt|All Files(*.*)|*.*";
                sfd.DefaultExt = "txt";
                sfd.DefaultFileName = "SharePointCSVImportErrorLog.txt";
                if (sfd.ShowDialog().Value)
                {
                    using (StreamWriter sw = new StreamWriter(sfd.OpenFile()))
                    {
                        sw.Write(errorLogText);
                        sw.AutoFlush = true;
                        sw.Flush();
                    }
                }
            }
        }

        private void NotifyError(string errorMessage)
        {
            this.Dispatcher.BeginInvoke(delegate()
               {
                   if (MessageBox.Show(errorMessage, "An Error Occurred", MessageBoxButton.OKCancel).Equals(MessageBoxResult.Cancel))
                   {

                       updater.Dispose();
                       UpdateProgress("Canceled Update because  of an error", 100);
                   }
               });
        }

        private void OnConfigured(bool value)
        {
            if (value)
            {
                this.UploadButton.IsEnabled = true;
            }
        }

        private void SelectFileButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Multiselect = false;
            dlg.Filter = "Text File (*.txt)|*.txt|CSV File (*.csv)|*.csv";
            bool? retval = dlg.ShowDialog();

            if (retval != null && retval == true)
            {
                dataFile = dlg.File;
                // UploadFile(dlg.File.Name, dlg.File.OpenRead());
                FileText.Text = dataFile.Name;
                this.ConfigureButton.IsEnabled = true;
            }
            else
            {
                FileText.Text = "No file selected...";
            }
        }

        private void UpdateProgress(string message, int completeNumber)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                if (this.ProgressPanel.Visibility == System.Windows.Visibility.Collapsed)
                {
                    this.ProgressPanel.Visibility = System.Windows.Visibility.Visible;
                }
                this.ProgressMessageTextBlock.Text = message;
                this.SatusProgressBar.Value = completeNumber;
            });
        }

        private void UploadButton_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult importContinue = MessageBox.Show("System will attempt to import data, continue?", "Import CSV Data", MessageBoxButton.OKCancel);
            if (dataFile != null)
            {
                if (importContinue == MessageBoxResult.OK)
                {
                    UpdateProgress("Parsing CSV File", 1);
                    Dictionary<int, List<string>> parsedData = CSVParser.CSVParseFile(dataFile.OpenRead());
                    UpdateProgress("Mapping Parsed CSV data", 5);
                    Dictionary<int, List<MappedValue>> mappedData = CSVParser.GetMappedValues(currentConfig.FieldMappings, parsedData);
                    updater = new ListItemUpdater(currentConfig.TargetWebUrl);
                    updater.UpdateFromCsV(mappedData, currentConfig.TargetListName, currentConfig.OverwriteExistingValues, currentConfig.DuplicateKeyAction, UpdateProgress, NotifyError, FinishedUpdating, ProcessFinished);
                }
            }
        }

        #endregion Methods
    }
}